<?php	
	require('config.php');
$version = '0.2';

$username = $_GET["username"];
$password = $_GET["pass"];
$user_hash = $_GET["hash"];
$function_id = $_GET["function_id"];
$function_args = $_GET["args"];
$current_user;
	
function syscall($function_id,$args)
{	
	//echo "sessions/".$_GET["username"]."/".$_GET["hash"];
	if( opendir("sessions/".$_GET["username"]."/".$_GET["hash"]) )
	{
		if($_GET["function_id"] == 01)
			return read();
		else if($_GET["function_id"] == 02)
			return write();
		else
			echo "FAIL001";
	}
	else
		echo "FAIL0010102";
};

	
function auth($username,$password)
{	
	global $user_dir;

	if($username  && $password )
	{
		if(readfile($user_dir."/".$username.".php"))
		{
			include($user_dir."/".$username.".php");

			if($user_password == $password)
			{
				$session_id = $_SERVER['REMOTE_ADDR'].$user_password.time();
				$session_id = md5($session_id);
				
				//create session directory
				mkdir("sessions/".$username."/".$session_id);
				//write session header at $username/$session_id/$session_header
				$session_file_name = "sessions/".$username."/".$session_id."/sessionHead.php";
				$session_info = time()."\n";
				$session_file_handle = fopen($session_file_name,'w');
				fwrite($session_file_handle,$session_info);
				echo $session_id;
				exit();
			}
			else
				echo 'FAIL@@';
		}
		else
		   echo 'FAIL11';
	}
	else
		echo 'FAIL00';
	return;
};

function read()
{
	//read and then write each message in the que, deleteing as we go
	//in production code this should be encrypted
	//echo "read()\n";
	$session_dir_handle = opendir("sessions/".$_GET["username"]."/".$_GET["hash"]);
	while (false !== ($file = readdir($session_dir_handle))) 
	{
		if($file != "." && $file !=".." && $file != "sessionHead.php")
		{
			echo readfile("sessions/".$_GET["username"]."/".$_GET["hash"]."/".$file);
			echo ";;\n";
			unlink("sessions/".$_GET["username"]."/".$_GET["hash"]."/".$file);
		}

    }
	echo "END_MESSAGE_STREAM";	
	closedir($session_dir_handle);
	exit();
};

function write()
{
	//write our $buffer data to a new message in each user's session
	//this info will be encrypted in production code
	//$message_file = "sessions/".$_GET["username"]."/".$_GET["hash"]."/".time();
	$message_file = time();
	$session_handle = opendir("sessions/".$_GET["username"]);
	while (false !== ($file = readdir($session_handle))) 
	{
		if($file != "." && $file !=".." && $file != $_GET["hash"])
		{
			$message_handle = fopen("sessions/".$_GET["username"]."/".$file."/".$message_file,"w");
			fwrite($message_handle,$_GET["message"]);
		}
		
    }
	echo "WRITE_MESSAGE_COMPLETE";
};

if(!$user_hash)
	return( auth($username,$password) );
else
	return( syscall($function_id,$function_args ));

?>







